import React, { PureComponent } from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';

import styles from './style.m.less';

export default class Textarea extends PureComponent {
    static propTypes = {
        className: PropTypes.string,
        placeholder: PropTypes.string,
        maxLength: PropTypes.number,
        textStyle: PropTypes.object,
        onChange: PropTypes.func,
        onFocus: PropTypes.func,
        onBlur: PropTypes.func,
        value: PropTypes.string,
        autoFocus: PropTypes.bool,
    };

    static defaultProps = {
        value: '',
        className: '',
        placeholder: '',
        maxLength: 2048,
        textStyle: {},
        onChange: () => {},
        onBlur: () => {},
        onFocus: () => {},
        autoFocus: false,
    };

    focus = () => {
        this.$textarea.focus();
    };

    blur = () => {
        this.$textarea.blur();
    };

    handleContentChange = e => {
        this.props.onChange(e.target.value);
    };

    // 处理pre最后一个字符是\n，但不渲染的feature
    handlePreContent = content => {
        if (content.endsWith('\n')) {
            return content + '\n'; // eslint-disable-line
        }
        return content;
    };

    render() {
        const {
            className, textStyle, value, placeholder, maxLength
        } = this.props;
        return (
            <div className={cx(styles.textareaBox, className)}>
                <pre className={styles.fakeTextarea} style={textStyle}>
                    {this.handlePreContent(value)}
                </pre>
                <textarea
                    ref={d => {
                        this.$textarea = d;
                    }}
                    className={styles.TextareaAutoheight}
                    style={textStyle}
                    value={value}
                    onChange={this.handleContentChange}
                    placeholder={placeholder}
                    maxLength={maxLength}
                    onBlur={this.props.onBlur}
                    onFocus={this.props.onFocus}
                    autoFocus={this.props.autoFocus}
                />
            </div>
        );
    }
}
